<template>
  <div>
    <el-form :model="form" ref="form" :rules="rules" label-width="120px">
      <el-table :data="form.tableData" border>
        <el-table-column prop="name" label="Name" width="180">
          <template slot-scope="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.name'" style="margin: 0;">
              <el-input v-model="scope.row.name"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="Age" width="180">
          <template slot-scope="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.age'" style="margin: 0;">
              <el-input v-model="scope.row.age"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addRow">Add Row</el-button>
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">Submit</el-button>
        <el-button @click="resetForm('form')">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        tableData: [
          { name: '', age: '' },
        ],
      },
      rules: {
        tableData: {
          type: 'array',
          required: true,
          validator: (rule, value, callback) => {
            for (let i = 0; i < value.length; i++) {
              if (!value[i].name || !value[i].age) {
                callback(new Error('Each row must have a name and age'));
                return;
              }
            }
            callback();
          },
        },
      },
    };
  },
  methods: {
    addRow() {
      this.form.tableData.push({ name: '', age: '' });
      this.updateRules();
    },
    updateRules() {
      this.$set(this.rules, 'tableData', {
        type: 'array',
        required: true,
        validator: (rule, value, callback) => {
          for (let i = 0; i < value.length; i++) {
            if (!value[i].name || !value[i].age) {
              callback(new Error('Each row must have a name and age'));
              return;
            }
          }
          callback();
        },
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('Submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
